﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.IO;
using AjaxControlToolkit;

namespace Department.admin.Content
{
    public partial class AddEvents : System.Web.UI.Page
    {
        const int MAX_FILE_SIZE = AdminVariablesSingleton.MAX_FILE_SIZE;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                Response.Redirect("/admin/Login.aspx");
            }
            this.Page.Title = "Добави събитие";

            AdminVariablesSingleton.configureCKEditor(ref TextBoxText);

        }

        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            FileInfo[] arrayWithFileNames = new FileInfo[3];
            arrayWithFileNames = this.uploadFiles();
            string eventID = "";
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlCommandText = "INSERT INTO Events (Name, PublishDate, EventDate, Description, TypeID, FacDeptID) VALUES (@Name, @PublishDate, @EventDate, @Description, (SELECT ID FROM Type WHERE Name = 'News'), dbo.uf_get_department_id())";
                SqlCommand saveToDB = new SqlCommand(sqlCommandText, conn);

                saveToDB.Parameters.AddWithValue("@Name", TextBoxHeading.Text);
                saveToDB.Parameters.AddWithValue("@PublishDate", DateTime.Now);
                saveToDB.Parameters.AddWithValue("@EventDate", Convert.ToDateTime(Date.Text));
                saveToDB.Parameters.AddWithValue("@Description", TextBoxText.Text);

                saveToDB.ExecuteNonQuery();

                string selectLastNewsIDText = "SELECT ID FROM Events WHERE ID = @@IDENTITY";
                SqlCommand selectLastNewsID = new SqlCommand(selectLastNewsIDText, conn);

                eventID = selectLastNewsID.ExecuteScalar().ToString();

            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }
            if (!eventID.Equals(""))
            {
                if (arrayWithFileNames[0] != null)
                {
                    insertDocumentForNews(arrayWithFileNames[0], eventID);
                }
                if (arrayWithFileNames[1] != null)
                {
                    insertDocumentForNews(arrayWithFileNames[1], eventID);
                }
                if (arrayWithFileNames[2] != null)
                {
                    insertDocumentForNews(arrayWithFileNames[2], eventID);
                }
            }
            Response.Redirect("~/admin/Content/ViewAllEvents.aspx");
        }

        protected void ButtonReset_Click(object sender, EventArgs e)
        {
            TextBoxHeading.Text = "";
            TextBoxText.Text = "";
        }
        protected FileInfo uploadFile(FileUpload fileControl)
        {
            if (fileControl.HasFile)
            {
                try
                {
                    if (fileControl.PostedFile.ContentLength < MAX_FILE_SIZE)
                    {
                        FileInfo fileInfo = new FileInfo();
                        string filename = Path.GetFileName(fileControl.FileName);
                        fileInfo.OriginalFileName = filename;

                        filename = DateTime.Now.ToUniversalTime().ToFileTimeUtc() + filename;
                        fileInfo.UniqueFileName = filename;

                        fileControl.SaveAs(Server.MapPath("~/files/uploadedFiles/") + filename);
                        fileInfo.FilePath = "~/files/uploadedFiles/" + filename;
                        return fileInfo;
                    }
                }
                catch (Exception ex)
                {
                    Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
                }
            }
            return null;
        }
        protected FileInfo[] uploadFiles()
        {
            FileInfo[] arrayWithFileNames = new FileInfo[3];
            int arrayCounter = 0;
            arrayWithFileNames[arrayCounter] = uploadFile(FileUploadControl);
            arrayCounter++;
            arrayWithFileNames[arrayCounter] = uploadFile(FileUploadControl2);
            arrayCounter++;
            arrayWithFileNames[arrayCounter] = uploadFile(FileUploadControl3);

            return arrayWithFileNames;
        }
        protected void insertDocumentForNews(FileInfo fileInfo, string eventID)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlCommandText = "INSERT INTO Documents (Name, Description, Link, TypeID, FacDeptID) VALUES (@Name, @Description, @Link, (SELECT ID FROM Type WHERE Name = 'Documents'), dbo.uf_get_department_id())";
                SqlCommand insertDocument = new SqlCommand(sqlCommandText, conn);

                insertDocument.Parameters.AddWithValue("@Name", fileInfo.OriginalFileName);
                insertDocument.Parameters.AddWithValue("@Description", fileInfo.UniqueFileName);
                insertDocument.Parameters.AddWithValue("@Link", fileInfo.FilePath);

                insertDocument.ExecuteNonQuery();

                string sqlCommandText2 = "INSERT INTO DocumentsForEvents (EventID, DocID) VALUES (@EventID, @@Identity)";
                SqlCommand insertDocumentForNews = new SqlCommand(sqlCommandText2, conn);

                insertDocumentForNews.Parameters.AddWithValue("@EventID", eventID);

                insertDocumentForNews.ExecuteNonQuery();
            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }

            finally
            {
                conn.Close();
            }

        }
    }
}